package com.grant.code.myblog.service.impl;

import com.grant.code.myblog.entity.User;
import com.grant.code.myblog.mapper.UserMapper;
import com.grant.code.myblog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public int register(User user) {
        // 设置默认值
        if (user.getNickname() == null) {
            user.setNickname(user.getUsername());
        }
        if (user.getAvatar() == null) {
            user.setAvatar("default-avatar.jpg");
        }
        if (user.getStatus() == null) {
            user.setStatus(1); // 默认正常状态
        }
        
        // 设置时间
        LocalDateTime now = LocalDateTime.now();
        user.setCreateTime(now);
        user.setUpdateTime(now);
        
        return userMapper.insert(user);
    }
    
    @Override
    public User login(String username, String password) {
        // 根据用户名查询用户信息
        User user = userMapper.selectByUsername(username);
        
        // 用户不存在或密码不匹配
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 简单密码验证（实际项目中应该使用加密验证）
        if (!password.equals(user.getPassword())) {
            throw new RuntimeException("密码错误");
        }
        
        // 判断用户状态
        if (user.getStatus() != null && user.getStatus() == 0) {
            throw new RuntimeException("账号已被禁用");
        }
        
        return user;
    }
}
